#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：wwdj_API 
@File    ：qw_message_push.py
@IDE     ：PyCharm 
@Author  ：我先测了
@Date    ：2024/11/27 14:38 
'''
import requests
import json
from operate.operate_excel import Operate_Excel
from data.details_data import Report_Details
import time

class WeChatWorkNotifier:
    def __init__(self, webhook_url=None):
        r = Report_Details()
        self.row = r.get_rows() - 1
        self.pass_total = r.get_pass_total()
        self.fail_number = r.get_fail_total()
        self.passing_rate = str(r.get_passing_rate())
        self.fail_detail = r.get_fail_details()
        if webhook_url != None:
            self.webhook_url = webhook_url
        else:
            self.webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=390f814b-09c1-4f8a-9c53-8864780037cd'

    # 获取接口执行结果数据
    def get_result(self):
        # 测试结果数据
        test_results = {
            "test_suite_name": "Example Test Suite",
            "total_tests": self.row,
            "passed_tests": self.pass_total,
            "failed_tests": self.fail_number,
            "Passing_rate": self.passing_rate+'%',
            "details": self.fail_detail
        }
        return test_results

    def send_message(self):
        """
        发送Markdown格式的消息到企业微信

        :param markdown_content: Markdown格式的消息内容
        """
        markdown_content = self.format_test_results()
        headers = {'Content-Type': 'application/json'}
        payload = {
            "msgtype": "markdown",
            "markdown": {
                "content": markdown_content
            }
        }
        response = requests.post(self.webhook_url, headers=headers, data=json.dumps(payload))

        if response.status_code == 200:
            print("消息发送成功")
        else:
            print(f"消息发送失败，状态码: {response.status_code}, 内容: {response.text}")

    def format_test_results(self):
        """
        格式化测试结果为Markdown格式的字符串

        :param test_results: 测试结果数据，通常是一个字典或对象
        :return: 格式化后的Markdown字符串
        """
        # 包含测试套件名称、总测试数、通过测试数和失败测试数的字典
        # 以及一个包含每个测试详细信息的列表
        MENTIONED_LIST = ['800114']
        test_results = self.get_result()
        markdown = f"""
# 接口测试报告
### 执行数据详情:
- 总接口数: {test_results['total_tests']}
- 通过接口数: <font color="info">{test_results['passed_tests']}</font>
- 失败接口数: <font color="warning">{test_results['failed_tests']}</font>
- 通过率: {test_results['Passing_rate']}
**报告时间：**{time.strftime('%Y-%m-%d %H:%M:%S')}
"""
        if  int(self.passing_rate) <100:
            markdown += """
            ### 失败接口如下:
                """
            for test in test_results['details']:
                markdown += f"-<font color='red'>{test['url_name']}:{test['test_name']}</font>-请<@{test['userid']}>及时处理!\n"

        return markdown


if __name__ == '__main__':
    r = WeChatWorkNotifier()
    print(r.format_test_results())

